<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="dialogCLose()"
  >
    <el-form
      class="form"
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-form-item
        label="会员卡号"
        prop="organName"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-select
          v-model="dataForm.type"
          placeholder="会员卡号请选择"
          @change="change1($event)"
          @visible-change="checked1($event)"
        >
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="单据日期"
        prop="operTimeStr"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-date-picker
          v-model="dataForm.operTimeStr"
          type="datetime"
          placeholder="选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="单据编号"
        prop="number"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          v-model="dataForm.number"
          placeholder="单据编号"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="付款类型"
        prop="payType"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input v-model="dataForm.payType" placeholder="付款类型"></el-input>
      </el-form-item>
      <el-form-item
        label="实收金额"
        prop="AllPrice"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          :value="AllPrice"
          placeholder="实收金额"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="收款金额"
        prop="AllPrice"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input
          :value="AllPrice"
          placeholder="收款金额"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <!-- <el-form-item
        label="找零"
        prop="payType"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-input v-model="dataForm.payType" placeholder="找零"></el-input>
      </el-form-item> -->
      <el-form-item
        label="收款账户"
        prop="accountName"
        :class="{ 'is-required': !dataForm.id }"
      >
        <el-select
          v-model="dataForm.type1"
          placeholder="收款账户请选择"
          @change="change2($event)"
          @visible-change="checked2($event)"
        >
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form ref="inServForm" label-width="130px" size="small" class="form1">
      <el-form-item label="" prop="servin">
        <el-button type="primary" @click="addRow(infiledList)">新增</el-button>
        <template>
          <el-table border :data="infiledList" style="width: 100%">
            <el-table-column prop="DepotName" label="仓库名称">
              <template scope="scope">
                <el-select
                  v-model="scope.row.DepotName"
                  clearable
                  @visible-change="checked($event)"
                  @change="change($event)"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item"
                    value-key="value"
                  >
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column
              prop="MaterialName"
              label="条码_名称(规格)(型号)(扩展信息)(单位)"
            >
              <template scope="scope">
                <!-- <el-select v-model="scope.row.MaterialName" clearable>
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select> -->
                <el-input
                  style="width: 100%"
                  placeholder="请选择商品信息"
                  v-model="scope.row.MaterialName"
                  :suffix-icon="
                    showTree ? 'el-icon-arrow-up' : 'el-icon-arrow-down'
                  "
                  @click.native="deptogglePanel($event, scope.$index)"
                  size="medium"
                  @input="input($event)"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="Stock" label="库存">
              <template scope="scope">
                <el-input size="mini" v-model="scope.row.Stock"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="Unit" label="单位">
              <template scope="scope">
                <el-input size="mini" v-model="scope.row.Unit"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="OperNumber" label="数量">
              <template scope="scope">
                <el-input size="mini" v-model="scope.row.OperNumber"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="UnitPrice" label="单价">
              <template scope="scope">
                <el-input size="mini" v-model="scope.row.UnitPrice"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="AllPrice" label="金额">
              <template scope="scope">
                <el-input
                  size="mini"
                  :value="Pricefloat(scope.$index)"
                  :disabled="true"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="Remark" label="备注">
              <template scope="scope">
                <el-input size="mini" v-model="scope.row.Remark"></el-input>
              </template>
            </el-table-column>
            <el-table-column fixed="right" label="操作">
              <template slot-scope="scope">
                <el-button
                  @click.native.prevent="deleteRow(scope.$index, infiledList)"
                  size="small"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        <div v-if="showTree" class="treeDiv" ref="tableList">
          <el-table
            @row-click="handleRegionNodeClick"
            ref="moviesTable"
            :data="memberList"
            border
            :cell-style="getCellStyle"
            :header-cell-style="getHeaderCellStyle"
            @cell-click="handleRegionNodeClick($event)"
          >
            <el-table-column
              v-for="(item, index) in Columns"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
export default {
  data() {
    return {
      infiledList: [],
      options: [],
      options1: [],
      options2: [],
      memberList: [], // 用户list
      showTree: false,
      selectTableId: "", //  table选中行id
      Columns: [
        {
          prop: "mBarCode",
          label: "条码",
        },
        {
          prop: "name",
          label: "名称",
        },
        {
          prop: "standard",
          label: "规格",
        },
        {
          prop: "model",
          label: "型号",
        },
        {
          prop: "unit",
          label: "单位",
        },
        {
          prop: "stock",
          label: "库存",
        },
        {
          prop: "inf",
          label: "扩展信息",
        },
      ],
      parentValue: [],
      value1: "",
      value2: "",
      depotId: "",
      value: "",
      datetime: "",
      visible: false,
      roleList: [],
      dataForm: {
        id: 0,
        organName: "",
        operTimeStr: "",
        DepotName: "",
        number: "",
        MaterialName: "",
        Stock: "",
        Unit: "",
        OperNumber: "",
        UnitPrice: "",
        payType: "",
        Remark: "",
        type: "",
        type1: "",
      },
      dataRule: {
        DepotName: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" },
        ],
        MaterialName: [
          {
            required: true,
            message: "条码_名称(规格)(型号)(扩展信息)(单位)不能为空",
            trigger: "blur",
          },
        ],
        Stock: [{ required: true, message: "库存不能为空", trigger: "blur" }],
        OperNumber: [
          { required: true, message: "数量不能为空", trigger: "blur" },
        ],
        UnitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" },
        ],
      },
      options: [],
      value: "",
      id: null,
      mId: null,
      curSelectIndex: null,
      organId: null,
      accountId: null,
    };
  },
  methods: {
    //总价的依赖属性
    Pricefloat(index) {
      return (
        this.infiledList[index].UnitPrice *
          this.infiledList[index].OperNumber || null
      );
    },
    AllPrice() {
      console.log(111);
    },
    deleteRow(index, rows) {
      //删除改行
      rows.splice(index, 1);
    },
    addRow(tableData) {
      // console.log(tableData)
      tableData.push({
        DepotName: "",
        MaterialName: "",
        Stock: "",
        Unit: "",
        OperNumber: "",
        UnitPrice: "",
        AllPrice: "",
        Remark: "",
      });
    },
    // 时间戳转成时间
    timestampToTime(timestamp) {
      var date = new Date(timestamp); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
      var Y = date.getFullYear() + "-";
      var M =
        (date.getHours() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      var h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      var m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      var s =
        (date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds()) +
        ":";
      return Y + M + D + h + m + s;
    },
    change(id) {
      console.log(id);
      this.id = id;
      return id;
      // this.id = id;
      // console.log(this.mId)
      if (id == null) {
        return;
      }
      this.getstock(id, this.mId);
    },
    checked(e) {
      if (e) {
      }
    },
    change1(id) {
      // console.log(id);
      this.organId = id;
    },
    checked1(e) {
      if (e) {
        this.getnum();
      }
    },
    getnum() {
      let str = `{"supplier":"","type":"会员","phonenum":"","telephone":"","description":""}`;
      var search = encodeURIComponent(str);
      this.$http({
        url: this.$http.adornUrl(`/supplier/list?search=${search}`),
        method: "get",
        params: this.$http.adornParams({
          currentPage: 1,
          pageSize: 1000,
        }),
      }).then((data) => {
        if (data.data && data.data.code === 0) {
          this.options1 = data.data.data.filter((fitem) => {
            // console.log(fitem)
            fitem.value = fitem.id;
            fitem.label = fitem.supplier;
            return fitem;
          });
        }
      });
    },
    change2(id) {
      // console.log(id);
      this.accountId = id;
    },
    checked2(e) {
      if (e) {
        this.getAccount();
      }
    },
    getAccount() {
      let str1 = `{"name":"","serialNo":"","remark":""}`;
      var search = encodeURIComponent(str1);
      this.$http({
        url: this.$http.adornUrl(`/account/list?search=${search}`),
        method: "get",
        params: this.$http.adornParams({
          currentPage: 1,
          pageSize: 1000,
        }),
      }).then((data) => {
        console.log(data);
        if (data.data && data.data.code === 0) {
          this.options2 = data.data.data.filter((fitem) => {
            // console.log(fitem)
            fitem.value = fitem.id;
            fitem.label = fitem.name;
            return fitem;
          });
        }
      });
    },
    // 输入框改变触发的函数
    input(event) {
      this.getMemberList();
      let value = event;
    },
    // 用户
    getMemberList() {
      this.$http({
        url: this.$http.adornUrl(`/material/findBySelect`),
        method: "get",
        params: this.$http.adornParams({
          q: "",
          page: 1,
          rows: 10,
          depotId: this.id,
          mpList: "undefined%2Cundefined%2Cundefined",
        }),
      }).then(({ data }) => {
        // console.log(data);
        this.memberList = data.data.rows;
        // console.log(this.memberList,data.data.rows)
      });
    },
    // 表格css
    getCellStyle() {
      return "text-align:center; ";
    },
    getHeaderCellStyle() {
      return "background: rgba(9, 37, 56,0.1);text-align:center; background: linear-gradient(to bottom,#ffffff 0,#eeeeee 100%);padding: 4px 5px;";
    },
    // 点击input 阻止冒泡 控制table显示隐藏
    deptogglePanel(event, cindex) {
      event || (event = window.event);
      event.stopPropagation
        ? event.stopPropagation()
        : (event.cancelBubble = true);
      this.showTree ? this.tableHide() : this.tableShow();
      this.getMemberList();
      this.curSelectIndex = cindex;
    },
    tableShow() {
      this.showTree = true;
      document.addEventListener("click", this.tableHideList, false);
    },
    tableHide() {
      this.showTree = false;
      document.addEventListener("click", this.tableHideList, false);
    },
    tableHideList(e) {
      if (this.$refs.tableList && !this.$refs.tableList.contains(e.target)) {
        this.tableHide();
      }
    },
    // 点击table节点
    handleRegionNodeClick(e) {
      // console.log(e);
      // console.log(e.Id);
      this.mId = e.Id;
      var str = `${e.MaterialName}${e.expand}${e.model}${e.name}${e.standard}${e.unit}`;
      this.infiledList.MaterialName = str; // 用户名字
      this.$http({
        url: this.$http.adornUrl(`/material/findByIdWithBarCode?meId=${e.Id}`),
        method: "get",
      }).then(({ data }) => {
        console.log(this.infiledList[this.curSelectIndex].MaterialExtendId);
        this.infiledList[this.curSelectIndex].MaterialName =
          data.data.mBarCode + "-" + data.data.name + "-" + data.data.model;
        this.infiledList[this.curSelectIndex].MaterialExtendId = e.Id;
        console.log(this.infiledList[this.curSelectIndex].DepotName);
        if (this.infiledList[this.curSelectIndex].DepotName == "") {
          console.log(1);
          return;
        }
        this.getstock(
          this.infiledList[this.curSelectIndex].DepotId,
          this.infiledList[this.curSelectIndex].MaterialExtendId
        );
      });

      this.showTree = false;
      // if (this.id == null) {
      //   return;
      // }
      // this.getstock(this.id, this.mId);
    },
    // 获取库存信息
    getstock(depotId, mId) {
      this.$http({
        url: this.$http.adornUrl(
          `/depotItem/findStockNumById?depotId=${depotId}&mId=${mId}`
        ),
        method: "get",
      }).then(({ data }) => {
        console.log(data.data.stock);
        this.dataForm.Stock = data.data.stock;
      });
    },
    init(
      id,
      organName,
      number,
      operTimeStr,
      payType,
      organId,
      accountId,
      accountName
    ) {
      console.log(
        id,
        organName,
        number,
        operTimeStr,
        payType,
        organId,
        accountId,
        accountName
      );
      this.dataForm.id = id || 0;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
        this.$refs["inServForm"].resetFields();
        this.$http({
          url: this.$http.adornUrl("/depot/findDepotByUserId"),
          method: "get",
          params: this.$http.adornParams({
            UBType: "UserDepot",
            UBKeyId: 63,
          }),
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.options = data.data.filter((fitem) => {
              fitem.value = fitem.id;
              fitem.label = fitem.depotName;
              return fitem;
            });
            console.log(this.options);
          }
        });

        if (this.dataForm.id) {
          this.organId = organId ? organId : "";
          this.accountId = accountId ? accountId : "";
          console.log(this.organId);
          this.$http({
            url: this.$http.adornUrl(`/depotItem/getDetailList`),
            method: "get",
            params: this.$http.adornParams(
              {
                headerId: this.dataForm.id,
                mpList: "undefined%2Cundefined%2Cundefined",
              },
              false
            ),
          }).then(({ data }) => {
            console.log(data.data.rows);
            if (data.data.rows.length == 0) {
              return;
            }
            this.infiledList = data.data.rows;
            console.log(this.infiledList);
            this.dataForm = data.data.rows[0];
            this.dataForm.id = id;
            this.dataForm.type = organName;
            this.dataForm.type1 = accountName;
            this.dataForm.number = number;
            this.dataForm.payType = payType;
            this.$set(this.dataForm, "operTimeStr", operTimeStr);
            this.id = data.data.rows[0].DepotId;
          });
        } else {
          this.$http({
            url: this.$http.adornUrl("/depotHead/buildNumber"),
            method: "get",
          }).then(({ data }) => {
            // console.log(data.DefaultNumber);
            this.dataForm.number = "LSTH" + data.DefaultNumber;
          });
          this.dataForm.id = id;
          this.dataForm.organName = organName;
          // console.log(new Date());
          this.$set(this.dataForm, "operTimeStr", new Date());
        }
      });
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          // 有传入的参数为修改  return之后为增加
          if (this.dataForm.id) {
            console.log(this.dataForm.type);
            let info = `{"Type":"入库","SubType":"零售退货","DefaultNumber":"${this.dataForm.number}","Number":"${this.dataForm.number}","LinkNumber":"","OperTime":"${this.dataForm.operTimeStr}","OrganId":"${this.organId}","Salesman":"","AccountId":"${this.accountId}","ChangeAmount":${this.AllPrice},"TotalPrice":"${this.AllPrice}","PayType":"现付","Remark":"","AccountMoneyList":"","Discount":"","DiscountMoney":"","DiscountLastMoney":"","OtherMoney":""}`;
            let rows =[]
            rows.push(${this.infiledList
                .map((iitem) => {
                  return `{"DepotId":"${
                    iitem.DepotName.id ? iitem.DepotName.id : iitem.DepotId
                  }","DepotName":"${
                    iitem.DepotName.depotName
                      ? iitem.DepotName.depotName
                      : iitem.DepotName
                  }","MaterialExtendId":"${iitem.MaterialExtendId}","Stock":"${
                    iitem.Stock
                  }","Unit":"${iitem.Unit}","OperNumber":"${
                    iitem.OperNumber
                  }","UnitPrice":"${iitem.UnitPrice}","AllPrice":"${
                    this.AllPrice
                  }","Remark":"${iitem.Remark}"},`;
                })
                .join("")})
            this.$http({
              url: this.$http.adornUrl(
                `/depotHead/updateDepotHeadAndDetail?id=${this.dataForm.id}`
              ),
              method: "post",
              data: this.$http.adornData(
                {
                  id: this.dataForm.id,
                  info,
                  preTotalPrice: this.AllPrice,
                  rows,
                },
                false
              ),
            }).then((data) => {
              console.log(data);
              // this.visible = false;
              if (data.data && data.data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  },
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          } else {
            //增加
            console.log(this.dataForm.type);
            var OperTime = this.dataForm.operTimeStr.getTime();
            OperTime = this.timestampToTime(OperTime);
            console.log(OperTime, 22222);
            let info = `{"Type":"入库","SubType":"零售退货","DefaultNumber":"${this.dataForm.number}","Number":"${this.dataForm.number}","LinkNumber":"","OperTime":"${OperTime}","OrganId":"${this.organId}","Salesman":"","AccountId":"${this.accountId}","ChangeAmount":${this.AllPrice},"TotalPrice":"${this.AllPrice}","PayType":"现付","Remark":"","AccountMoneyList":"","Discount":"","DiscountMoney":"","DiscountLastMoney":"","OtherMoney":""}`;
            let rows = `[
              ${this.infiledList
                .map((iitem) => {
                  return `{"DepotId":"${
                    iitem.DepotName.id ? iitem.DepotName.id : iitem.DepotId
                  }","DepotName":"${
                    iitem.DepotName.depotName
                      ? iitem.DepotName.depotName
                      : iitem.DepotName
                  }","MaterialExtendId":"${iitem.MaterialExtendId}","Stock":"${
                    iitem.Stock
                  }","Unit":"${iitem.Unit}","OperNumber":"${
                    iitem.OperNumber
                  }","UnitPrice":"${iitem.UnitPrice}","AllPrice":"${
                    this.AllPrice
                  }","Remark":"${iitem.Remark}"},`;
                })
                .join("")}
            ]`;
            this.$http({
              url: this.$http.adornUrl(`/depotHead/addDepotHeadAndDetail`),
              method: "post",
              data: this.$http.adornData(
                {
                  info,
                  rows,
                },
                false
              ),
            }).then((data) => {
              // console.log(data);
              this.visible = false;
              this.$emit("refreshDataList");
            });
          }
        }
      });
    },
    dialogCLose() {
      this.infiledList = [];
      this.curSelectIndex = null;
      this.dataForm = {
        id: 0,
        organName: "",
        operTimeStr: "",
        DepotName: "",
        number: "",
        MaterialName: "",
        Stock: "",
        Unit: "",
        OperNumber: "",
        UnitPrice: "",
        payType: "",
        Remark: "",
      };
    },
  },
  computed: {
    AllPrice: {
      get: function () {
        let total = 0;
        if (this.infiledList.length == 0) {
          return;
        }
        this.infiledList.map((item) => {
          total += item.OperNumber * item.UnitPrice;
        });
        return total;
      },
      set: function () {
        return 0;
      },
    },
  },
  mounted(){
    this.getAccount();
    this.getnum();
  }
};
</script>
<style scoped>
.form .el-input__inner {
  width: 220px;
}
.form .el-form-item {
  display: inline-block;
  width: 33%;
}
element.style {
  width: 900px;
}
.el-form-item__content {
  margin-left: 0px;
}
.form1 {
  margin-left: -100px !important;
}
</style>

